<template>
  <div class="healthInfo padding_20">
    <el-input v-model="param.searchCondition"
              placeholder="请输入标题"
              class="w-200"
              clearable
              @clear="handleQuery"></el-input>
    <el-select v-model="param.type"
               class="w-200"
               clearable
               placeholder="请选择文章分类"
               @change="handleQuery"
               @clear="handleQuery">
      <el-option v-for="item in typeItems"
                 :key="item.value"
                 :label="item.label"
                 :value="item.value">
      </el-option>
    </el-select>
    <el-button @click="handleQuery"
               type="primary">查 询
    </el-button>
    <el-button @click="handleAdd"
               type="primary">新 增
    </el-button>

    <el-table stripe
              :data="tableData"
              style="width: 100%"
              border
              class="mt-20">
      <el-table-column align="center"
                       type="index"
                       min-width="20">
      </el-table-column>
      <el-table-column align="center"
                       prop="title"
                       label="标题"
                       min-width="500">
      </el-table-column>
      <el-table-column align="center"
                       prop="type"
                       label="文章分类"
                       :formatter="formatterType"
                       min-width="150">
      </el-table-column>
      <el-table-column align="center"
                       prop="sourceName"
                       label="作者/来源"
                       min-width="150">
      </el-table-column>
      <el-table-column align="center"
                       label="资讯类型"
                       :formatter="formatterTypeName"
                       min-width="100">
      </el-table-column>
      <el-table-column align="center"
                       prop="createTime"
                       label="发布时间"
                       width="150"
                       :formatter="formatterDate">
      </el-table-column>
      <el-table-column align="center"
                       prop="isTop"
                       label="是否置顶"
                       width="100"
                       :formatter="formatterIsTop">
      </el-table-column>
      <el-table-column align="center"
                       width="180"
                       label="操作">
        <template slot-scope="scope">
          <el-button type="primary"
                     @click="handleEdit(scope.row)">编 辑
          </el-button>
          <el-button type="danger"
                     @click="handleDel(scope.row)">删 除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <page @getList="_getList"
          :pageTotal="pageTotal"
          ref="page"></page>
    <el-dialog
      width="70%"
      title="新增/编辑"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
               :rules="rules"
               ref="sizeForm"
               label-position="right"
               label-width="85px"
               :model="sizeForm">
        <div class="info"
             :style="{'left': (sizeForm.contentType === 1 ? '70%' : '31%')}">

          <el-form-item label="标题"
                        prop="title">
            <el-input v-model="sizeForm.title"></el-input>
          </el-form-item>
          <!--<el-form-item label="作者">
            <el-input v-model="sizeForm.author"></el-input>
          </el-form-item>-->
          <el-form-item label="作者/来源"
                        prop="sourceName">
            <el-input v-model="sizeForm.sourceName"></el-input>
          </el-form-item>
          <el-form-item label="摘要"
                        prop="summary">
            <el-input style="width: 90%;"
                      type="textarea"
                      :rows="5"
                      placeholder="请输入摘要..."
                      v-model="sizeForm.summary"></el-input>
          </el-form-item>
          <el-form-item label="是否置顶"
                        prop="isTop">
            <el-checkbox v-model="sizeForm.isTop"></el-checkbox>
          </el-form-item>
          <el-form-item label="封面图"
                        prop="imageUrl">
            <el-upload class="avatar-uploader"
                       :action="uploadImgUrl"
                       :show-file-list="false"
                       :on-success="handleAvatarSuccess"
                       :before-upload="beforeAvatarUpload">
              <img v-if="sizeForm.imageUrl"
                   :src="sizeForm.imageUrl"
                   class="avatar">
              <i v-else
                 class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="文章分类"
                        prop="type">
            <el-select v-model="sizeForm.type"
                       placeholder="请选择文章分类">
              <el-option v-for="item in typeItems"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="资讯类型">
            <el-select v-model="sizeForm.informationTypeId"
                       placeholder="请选择资讯类型...">
              <el-option v-for="item in informationTypeOptions"
                         :key="item.id"
                         :label="item.informationTypeName"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容类型"
                        prop="contentType">
            <el-select v-model="sizeForm.contentType"
                       placeholder="请选择">
              <el-option v-for="item in typeOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="阅读次数"
                        class="is-required"
                        prop="readTimes">
            <el-input v-model.number="sizeForm.readTimes"></el-input>
          </el-form-item>
            <el-form-item  v-if="sizeForm.contentType === 1">
              <div>
                <vue-neditor-wrap
                  :destroy="true"
                  v-model="sizeForm.content"
                  :config="myConfig"></vue-neditor-wrap>

              </div>
            </el-form-item>

          <el-form-item v-if="sizeForm.contentType === 2"
                        label="外链URL">
            <el-input v-model="sizeForm.linkUrl"></el-input>
          </el-form-item>
        </div>
      </el-form>

      <p align="center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary"
                   @click="handleSave('sizeForm')">确 定
        </el-button>
      </p>


    </el-dialog>
  </div>
</template>

<script>
import Page from '@/base/page/page'
import {mapGetters} from 'vuex'
import VueNeditorWrap from 'vue-neditor-wrap'

export default {
  name: "healthInfo",
  data() {
    return {
      myConfig: {
        // 你的UEditor资源存放的路径,相对于打包后的index.html
        UEDITOR_HOME_URL: this.api.uEditorHomeUrl,
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: '418',
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 关闭自动保存
        enableAutoSave: false,
        scaleEnabled: true
      },
      resetKey: true,
      tableData: [],
      pageTotal: 0,       //总条数
      dialogVisible: false,
      fullscreen: true,
      param: {
        type: null,
        typeList: [1, 2, 7],
        searchCondition: ''
      },
      labelPosition: 'right',
      uploadImgUrl: this.api.file.uploadImage,
      sizeForm: {
        informationTypeId: '',
        title: '',
        imageUrl: '',
        type: '',
        contentType: 2,
        content: '',
        linkUrl: '',
        // author: '',
        sourceName: '',
        summary: '',
        isTop: false,
        readTimes: ''
      },
      rules: {
        title: [{required: true, message: '标题不能为空', trigger: 'blur'}],
        sourceName: [{required: true, message: '来源/作者不能为空', trigger: 'blur'}],
        imageUrl: [{required: true, message: '封面图不能为空', trigger: 'blur'}],
        contentType: [{required: true, message: '内容类型不能为空', trigger: 'blur'}],
        informationTypeId: [{required: true, message: '请选择资讯类型', trigger: 'blur'}],
        type: [{required: true, message: '内容分类不能为空', trigger: 'blur'}],
        readTimes: [{required: false, type: 'number', message: '阅读次数必须为数字值', trigger: 'blur'}],
      },
      typeOptions: [
        {
          value: 1,
          label: '富文本'
        },
        {
          value: 2,
          label: '外链URL'
        }
      ],
      typeItems: [
        {
          value: 1,
          label: '健康咨询'
        },
        {
          value: 2,
          label: '行业咨询'
        },
        {
          value: 7,
          label: '天下医生'
        }
      ],
      informationTypeOptions: []
    }
  },
  watch: {
    'sizeForm.contentType': function () {
      this.$nextTick(() => {
        if (this.sizeForm.contentType === 2) {
          if (this.$refs.sizeForm.$el.getElementsByTagName("textarea")[1] != undefined) {
            this.$refs.sizeForm.$el.getElementsByTagName("textarea")[1].remove()
          }
        }
      })
    },
    dialogVisible: function () {
      let param = {
        type: 1,
        pageIndex: 0,
        pageSize: 100
      };
      if (this.dialogVisible) {
        this.post(this.api.informationTypeList.selectPageAll, param).then((res) => {
          if (res.data.code === '200') {
            this.informationTypeOptions = res.data.object;
            this.informationTypeOptions.forEach((item, index) => {
              if (item.isModify === 1) {
                this.informationTypeOptions.splice(index, 1)
              }
            })
          }
        })
      }
      if (!this.dialogVisible) {
        this.$nextTick(() => {
          this.sizeForm = {
            informationTypeId: '',
            title: '',
            imageUrl: '',
            type: '',
            contentType: 2,
            content: '',
            linkUrl: '',
            // author: '',
            sourceName: '',
            summary: '',
            isTop: false,
            readTimes: ''
          }
        })
      }
    }
  },
  mounted() {
    this._getList()
  },
  methods: {
    handleQuery() {
      this.page.pageIndex = 0;
      this._getList()
    },
    handleAdd() {
      this.sizeForm.type = this.param.type;
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogVisible = true;
      this.sizeForm = row;
      this.sizeForm.isTop = this.sizeForm.isTop === 1 ? true : false
    },
    handleDel(row) {
      this.$confirm('您确认删除该信息？')
        .then(_ => {
          this.ajax({
            type: this.api.informationDel.type,
            url: this.api.informationDel.url,
            data: {id: row.id},
            success: (data) => {
              this.$message.success('删除成功!');
              this._getList()
            },
            error: (data) => {
              this.$Message.error(data.message);
            }
          })
        })
        .catch(_ => {
        });
    },
    _getList() {
      this.ajax({
        type: this.api.informationList.type,
        url: this.api.informationList.url,
        data: Object.assign({}, this.page, this.param),
        success: (data) => {
          this.tableData = data.object
          this.pageTotal = data.totalNum
        },
        error: (data) => {
          this.$Message.error(data.message);
        }
      })
    },
    formatterDate(row) {
      return this.commonFunction.timestampFormat(new Date(row.createTime), 'yyyy-MM-dd hh:mm:ss')
    },
    formatterIsTop(row) {
      let isTop = ["否", "是"];
      return isTop[row.isTop]
    },
    formatterTypeName(row) {
      if (row.informationTypeDto != null) {
        return row.informationTypeDto.informationTypeName
      }
    },
    formatterType(row) {
      let typeItems = this.typeItems;
      for (let i = 0; i < typeItems.length; i++) {
        if (row.type === typeItems[i].value) {
          return typeItems[i].label;
        }
      }
      return "";
    },
    catchData: function (html) {
      this.sizeForm.content = html
    },
    handleAvatarSuccess(res) {
      this.sizeForm.imageUrl = res.url;
    },
    beforeAvatarUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isLt10M;
    },
    handleSave(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.sizeForm.isTop) {
            this.sizeForm.isTop = 1
          } else {
            this.sizeForm.isTop = 0
          }
          this.post(this.api.informationSave.uploadInfo, this.sizeForm).then((res) => {
            if (res.data.code === '200') {
              this.$message({
                showClose: true,
                message: "保存成功",
                type: 'success'
              });
              this.dialogVisible = false;
              this._getList()
            } else {
              this.$message({
                showClose: true,
                message: res.data.message,
                type: 'error'
              })
            }
          })
        }
      })
    },
    cancel() {
      this.dialogVisible = false;
      this._getList()
    }
  },
  computed: {
    ...mapGetters([
      'page'
    ])
  },
  components: {
    Page,
    VueNeditorWrap
  }
}
</script>

<style scoped lang="scss" type="text/scss" rel="stylesheet/scss">


.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #606266;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 98px;
  height: 98px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}


</style>
